package com.wie.staffhubpro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wie.staffhubpro.constant.MessageConstant;
import com.wie.staffhubpro.domain.dto.IndicatorSubmitDTO;
import com.wie.staffhubpro.domain.entity.*;
import com.wie.staffhubpro.exception.DataErrorException;
import com.wie.staffhubpro.mapper.SingleIndicatorEmpMapper;
import com.wie.staffhubpro.mapper.TotalIndicatorMapper;
import com.wie.staffhubpro.service.SingleIndicatorService;
import com.wie.staffhubpro.mapper.SingleIndicatorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.Year;
import java.util.ArrayList;
import java.util.List;

/**
* @author WiedersehenM
* @description 针对表【single_indicator】的数据库操作Service实现
* @createDate 2025-07-02 17:05:44
*/
@Service
public class SingleIndicatorServiceImpl extends ServiceImpl<SingleIndicatorMapper, SingleIndicator>
    implements SingleIndicatorService{

    @Autowired
    private SingleIndicatorMapper singleIndicatorMapper;

    @Autowired
    private SingleIndicatorEmpMapper singleIndicatorEmpMapper;

    @Autowired
    private TotalIndicatorMapper totalIndicatorMapper;

    /**
     * 评分
     */
    @Transactional
    public void rate(IndicatorSubmitDTO indicatorSubmitDTO) {
        // 插入数据
        QueryWrapper<SingleIndicator> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        List<SingleIndicator> singleIndicatorList = singleIndicatorMapper.selectList(queryWrapper);
        Integer perId = 1;
        if (!singleIndicatorList.isEmpty()) {
            perId = singleIndicatorList.get(0).getId() + 1;
        }
        SingleIndicator singleIndicator = new SingleIndicator().builder()
                .id(perId)
                .score(indicatorSubmitDTO.getScore())
                .evaluation(indicatorSubmitDTO.getEvaluation())
                .createTime(LocalDateTime.now())
                .build();
        singleIndicatorMapper.insert(singleIndicator);
        SingleIndicatorEmp singleIndicatorEmp = new SingleIndicatorEmp().builder()
                .perId(perId)
                .empId(indicatorSubmitDTO.getEmpId())
                .indId(indicatorSubmitDTO.getIndId())
                .build();
        singleIndicatorEmpMapper.insert(singleIndicatorEmp);
        // 计算新的总评，并更新
        CalculateIndicator calculateIndicator = new CalculateIndicator().builder()
                .empId(indicatorSubmitDTO.getEmpId())
                .indId(indicatorSubmitDTO.getIndId())
                .build();
        calculate(calculateIndicator);
    }


    /**
     * 计算总评
     */
    @Transactional
    public void calculate (CalculateIndicator calculateIndicator) {
        // 查找今年该员工的所有评分
        List<ComprehensiveIndicator> comIndList = singleIndicatorEmpMapper.selectComprehensive(calculateIndicator);
        // 计算该员工总评
        // 根据 indId 给查询到的所有 list 分组
        List<ComprehensiveIndicator> ind1 = new ArrayList<>();
        Integer score1 = 0;
        List<ComprehensiveIndicator> ind2 = new ArrayList<>();
        Integer score2 = 0;
        List<ComprehensiveIndicator> ind3 = new ArrayList<>();
        Integer score3 = 0;
        for (ComprehensiveIndicator comInd : comIndList) {
            if (comInd.getIndId() == 1) {
                ind1.add(comInd);
            } else if (comInd.getIndId() == 2) {
                ind2.add(comInd);
            } else {
                ind3.add(comInd);
            }
        }
        if (!ind1.isEmpty()) {
            score1 = Integer.valueOf(ind1.get(0).getScore());
        }
        if (!ind2.isEmpty()) {
            score2 = Integer.valueOf(ind2.get(0).getScore());
        }
        Integer total = 0;
        Integer count = 0;
        if (!ind3.isEmpty()) {
            for (ComprehensiveIndicator indicator : comIndList) {
                if (indicator != null && indicator.getScore() != null) {
                    Integer tempScore = Integer.valueOf(indicator.getScore());
                    total += tempScore;
                    count++;
                }
            }
        }
        if (count != 0) {
            score3 = total / count;
        }
        String totalScore = String.valueOf(score1 * 0.3 + score2 * 0.2 + score3 * 0.5);
        // 查找该员工的总评
        QueryWrapper<TotalIndicator> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("emp_id", calculateIndicator.getEmpId())
                .eq("year", Year.now().toString());
        List<TotalIndicator> indicatorList = totalIndicatorMapper.selectList(queryWrapper);
        if (indicatorList.size() != 1) {
            throw new DataErrorException(MessageConstant.DATA_ERROR);
        }
        // 更新员工总评信息
        TotalIndicator totalIndicator = indicatorList.get(0);
        totalIndicator.setTotalScore(totalScore);
        totalIndicatorMapper.updateById(totalIndicator);
    }

}




